// 导入动态路由和静态路由
import { asyncRouterMap, staticRouterMap } from "@/router";
// Object.assign不兼容IE
// if (typeof Object.assign != 'function') {
//   Object.assign = function(target) {
//     'use strict';
//     if (target == null) {
//       throw new TypeError('Cannot convert undefined or null to object');
//     }
//     target = Object(target);
//     for (var index = 1; index < arguments.length; index++) {
//       var source = arguments[index];
//       if (source != null) {
//         for (var key in source) {
//           if (Object.prototype.hasOwnProperty.call(source, key)) {
//             target[key] = source[key];
//           }
//         }
//       }
//     }
//     return target;
//   };
// }
// 筛选出有权限路由
function filterRouter(userRouter = [], allRouter = []) {
  return userRouter
    .map((menuItem) => {
      const routerItem = allRouter.find((item) => item.name === menuItem.name);
      const icon = routerItem && routerItem.meta && routerItem.meta.icon ? routerItem.meta.icon : "icon-nav0";
      const metaObj = routerItem && routerItem.meta ? routerItem.meta : {};
      // console.log('Layout', process.env.NODE_ENV);
      // console.log('Layout', process.env.VUE_APP_LAYOUT);
      return {
        path: "/" + menuItem.name,
        name: menuItem.name,
        component: () => {
          if (process.env.VUE_APP_LAYOUT == 'noMenu') {
            // 山西省公共资源电子监管系统
            return import('@/layout/noMenu.vue');
          }
          return import('@/layout/default.vue');
        },
        ...(routerItem ? routerItem : {}),
        meta: Object.assign(metaObj, {
          title: menuItem.title,
          index: menuItem.index,
          key: menuItem.name,
          showChild: JSON.parse(menuItem.showChild),
          icon: menuItem.icon ? menuItem.icon : icon
        }),
        children:
          menuItem.children.length && !menuItem.children[0].name.includes("BUTTON")
            ? filterRouter(menuItem.children, allRouter)
            : []
      };
    })
    .sort((a, b) => a.meta.index - b.meta.index);
}
// 递归为所有有子路由的路由设置全path
function setPath(routes) {
  routes.forEach((item) => {
    const prentPath = item.path;
    const metaKey = item.meta.key;
    if (item.meta.showChild && item.children.length > 0) {
      for (let i = 0; i < item.children.length; i++) {
        item.children[i].path = prentPath + item.children[i].path;
        item.children[i].meta.key = metaKey;
      }
      setPath(item.children);
    } else if (!item.meta.showChild && item.children.length > 0) {
      for (let i = 0; i < item.children.length; i++) {
        // console.log(prentPath, item.children[i].path)
        item.children[i].path = prentPath + item.children[i].path;
        item.children[i].meta.key = metaKey;
        item.children[i].meta.prentPath = prentPath;
      }
    } else {
      item.meta.key = metaKey;
    }
  });
  return routes;
}
// 递归为所有有子路由的路由设置第一个children.path为默认路由
function setDefaultRoute(routes) {
  routes.forEach((v, i) => {
    if (v.children && v.children.length > 0) {
      v.redirect = `${v.name}/${v.children[0].name}`;
      setDefaultRoute(v.children);
    }
  });
  return routes;
}
const permission = {
  state: {
    routers: staticRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      // 设置全路径
      state.addRouters = setDefaultRoute(setPath(routers));
      const tempRouter = staticRouterMap.concat(routers);
      tempRouter.push({
        path: "*",
        redirect: "/"
      });
      state.routers = tempRouter;
    }
  },
  actions: {
    generateRoutes({ commit }, data) {
      return new Promise((resolve) => {
        // commit("SET_ROLES", data);
        if (data.roles) {
          const { roles } = data;
          const system = data.systemName;
          const { tabs } = data;
          commit("SET_TABS", tabs);
          commit("SET_ROLES", roles);
          commit("SET_SYSTEM", system);
        } else {
          commit("SET_ROLES", data);
        }
        commit("SET_ROUTERS", filterRouter(data.roles || data, asyncRouterMap));
        resolve();
      });
    }
  }
};
export default permission;
